package cate.game.role.pvp.eliterace.msg;

import cate.game.GameBody;
import cate.game.client.ClientContext;
import cate.game.client.msg.ClientMsg;
import cate.game.client.msg.MsgConfig;
import cate.game.client.msg.MsgInput;
import cate.game.pvp.eliterace.data.EliteRaceKV;
import cate.game.pvp.eliterace.data.EliteRaceSpec;
import cate.game.pvp.eliterace.util.EliteRaceSpecUtils;
import cate.game.role.pvp.eliterace.vo.EliteRaceBetVO;

import java.util.AbstractMap;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;

import static cate.game.client.msg.MsgSender.send;
import static cate.game.client.msg.id.MsgIdBEliteRace.BET_RECORD_REQ;
import static cate.game.pvp.eliterace.util.EliteRaceSpecUtils.deserialize;

@ClientMsg(title = "精英赛 竞猜记录 请求")
public class EliteRaceBetRecordReq implements MsgInput {

    @Override
    public MsgConfig conf() {
        return BET_RECORD_REQ;
    }

    @Override
    public void execute(GameBody game, ClientContext cc) {
        EliteRaceKV kv = game.pvp.eliteRace.getHandler().getDataManager().getData();
        Map<EliteRaceSpec, EliteRaceBetVO> rdMap = cc.getRole().getPvp().eliteRace.betPO.getRdMap()
                .entrySet()
                .stream()
                .map(this::mapMap)
                .filter(Optional::isPresent)
                .map(Optional::get)
                .filter(entry -> entry.getKey().getPeriod() < kv.getSpec().getPeriod()
                        || (entry.getKey().getPeriod() == kv.getSpec().getPeriod() && entry.getKey().getRound() < kv.getSpec().getRound())
                        || (kv.getSpec().getStep() - entry.getKey().getStep() > 2))
                .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
        send(cc::sendNow, new EliteRaceBetRecordResp(rdMap));
    }

    private Optional<Map.Entry<EliteRaceSpec, EliteRaceBetVO>> mapMap(Map.Entry<String, EliteRaceBetVO> entry) {
        return Optional.ofNullable(deserialize(entry.getKey()))
                .map(spec -> new AbstractMap.SimpleEntry<>(spec, entry.getValue()));
    }
}
